package com.my.bigsite.modules.act.web.Leave;

import org.activiti.engine.ActivitiException;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.IdentityLinkType;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.my.bigsite.common.util.Page;
import com.my.bigsite.common.util.PageUtil;
import com.my.bigsite.common.util.UserUtil;
import com.my.bigsite.common.web.BaseController;
import com.my.bigsite.modules.act.entity.Leave;
import com.my.bigsite.modules.act.service.ActLeaveService;
import com.my.bigsite.modules.act.service.LeaveWorkflowService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 请假控制器，包含保存、启动流程
 *
 * @author HenryYan
 */
@Controller
@RequestMapping(value = "${adminPath}/oa/leave")
public class LeaveController  extends BaseController{

    private Logger logger = LoggerFactory.getLogger(getClass());

 

    @Autowired
    protected RuntimeService runtimeService;
 
    @Autowired
    protected TaskService taskService;

    @Autowired
    protected LeaveWorkflowService workflowService;
    
    @Autowired
    protected ActLeaveService actLeaveService;
    @RequestMapping(value = {"apply", ""})
    public String createForm(Model model) {
        model.addAttribute("leave", new Leave());
        return "modules/act/oaleave/leaveApply";
    }

    /**
     * 启动请假流程
     *
     * @param leave
     */ 
    @RequestMapping(value = "start", method = RequestMethod.POST)
    public String startWorkflow(String startTime,String endTime,String leaveType, String reason, RedirectAttributes redirectAttributes, HttpSession session) {
        try {
            String username=UserUtil.getUserFromSession(session).getId(); 
            logger.info("开始请假:"+username);
            // 用户未登录不能操作，实际应用使用权限框架实现，例如Spring Security、Shiro等
            if (username == null || StringUtils.isBlank(username)) {
                return "redirect:/login?timeout=true";
            }
            SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Leave leave=new Leave();
            leave.setId(System.currentTimeMillis());
            leave.setUserId(username);
            leave.setLeaveType(leaveType);
            leave.setStartTime(sFormat.parse(startTime));
            leave.setEndTime(sFormat.parse(endTime));
            leave.setApplyTime(sFormat.parse(startTime));
            leave.setReason(reason);
            Map<String, Object> variables = new HashMap<String, Object>();
            ProcessInstance processInstance = workflowService.startWorkflow(leave, variables);
            redirectAttributes.addFlashAttribute("message", "流程已启动，流程ID：" + processInstance.getId());
        } catch (ActivitiException e) {
            if (e.getMessage().indexOf("no processes deployed with key") != -1) {
                logger.warn("没有部署流程!", e);
                redirectAttributes.addFlashAttribute("error", "没有部署流程，请在[工作流]->[流程管理]页面点击<重新部署流程>");
            } else {
                logger.error("启动请假流程失败：", e);
                redirectAttributes.addFlashAttribute("error", "系统内部错误！");
            }
        } catch (Exception e) {
            logger.error("启动请假流程失败：", e);
            redirectAttributes.addFlashAttribute("error", "系统内部错误！");
        }
        return "redirect:"+adminPath+"/oa/leave/list/task";
    }
     /**
     * 任务列表
     *
     * @param leave
     */ 
    @RequestMapping(value = "list/task")
    public ModelAndView taskList(HttpSession session, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("modules/act/oaleave/taskList");
        Page<Leave> page = new Page<Leave>(PageUtil.PAGE_SIZE);
        Page<Leave> page2 = new Page<Leave>(PageUtil.PAGE_SIZE);
        int[] pageParams = PageUtil.init(page, request);

        String userId = UserUtil.getUserFromSession(session).getId();
        workflowService.findTodoTasks(userId, page, pageParams);
        workflowService.findTodoTasks2(userId, page2, pageParams);
        mav.addObject("page", page);
        mav.addObject("page2", page2);
        return mav;
    } 

    /**
     * 读取运行中的流程实例
     *
     * @return
     *//*
    @RequestMapping(value = "list/running")
    public ModelAndView runningList(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/oa/leave/running");
        Page<Leave> page = new Page<Leave>(PageUtil.PAGE_SIZE);
        int[] pageParams = PageUtil.init(page, request);
        workflowService.findRunningProcessInstaces(page, pageParams);
        mav.addObject("page", page);
        return mav;
    }

    *//**
     * 读取运行中的流程实例
     *
     * @return
     *//*
    @RequestMapping(value = "list/finished")
    public ModelAndView finishedList(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/oa/leave/finished");
        Page<Leave> page = new Page<Leave>(PageUtil.PAGE_SIZE);
        int[] pageParams = PageUtil.init(page, request);
        workflowService.findFinishedProcessInstaces(page, pageParams);
        mav.addObject("page", page);
        return mav;
    }

    *//**
     * 签收任务
     */ 
    @RequestMapping(value = "task/claim/{id}")
    public String claim(@PathVariable("id") String taskId, HttpSession session, RedirectAttributes redirectAttributes) {
        String userId = UserUtil.getUserFromSession(session).getId(); 
        taskService.claim(taskId, userId);
        redirectAttributes.addFlashAttribute("message", "任务已签收");
        return "redirect:"+adminPath+"/oa/leave/list/task";
    }

     /**
     * 读取详细数据
     *
     * @param id
     * @return
     *//*
    @RequestMapping(value = "detail/{id}")
    @ResponseBody
    public Leave getLeave(@PathVariable("id") Long id) {
        Leave leave = leaveManager.getLeave(id);
        return leave;
    }

    *//**
     * 读取详细数据
     *
     * @param id
     * @return
     *//*
    @RequestMapping(value = "detail-with-vars/{id}/{taskId}")
    @ResponseBody
    public Leave getLeaveWithVars(@PathVariable("id") Long id, @PathVariable("taskId") String taskId) {
        Leave leave = leaveManager.getLeave(id);
        Map<String, Object> variables = taskService.getVariables(taskId);
        leave.setVariables(variables);
        return leave;
    }

    *//**
     * 完成任务
     *
     * @param id
     * @return
     *//*
    @RequestMapping(value = "complete/{id}", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String complete(@PathVariable("id") String taskId, Variable var) {
        try {
            Map<String, Object> variables = var.getVariableMap();
            taskService.complete(taskId, variables);
            return "success";
        } catch (Exception e) {
            logger.error("error on complete task {}, variables={}", new Object[]{taskId, var.getVariableMap(), e});
            return "error";
        }
    }
*/
    
    /**
    * 沟通
    *
    * @param taskid userid
    * @return
    */ 
   @RequestMapping(value = "communicate/{taskid}/{userid}")
   public String getLeaveWithVars(@PathVariable("userid") String userid, @PathVariable("taskid") String taskId) {
	   logger.info("沟通发送成功"+userid+""+taskId);
	   taskService.addUserIdentityLink(taskId, userid, IdentityLinkType.PARTICIPANT);
	  
       logger.info("沟通发送成功");
	   return  "redirect:/modules/act/oaleave/list/task";
   }
   
   
	/**
	 * 反馈.
	 * @return
	 */
	@RequestMapping(value = "comment")
	public String comment( String taskId, String processInstanceId,String msg,HttpSession session){
		String userId = UserUtil.getUserFromSession(session).getId(); 
		 Authentication.setAuthenticatedUserId(userId);//批注人的名称  一定要写，不然查看的时候不知道人物信息
		 taskService.addComment(taskId, processInstanceId, msg);
		return "modules/act/actTaskTodoList";
	}
	

    /**
     * 读取详细数据
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "detail/{id}")
    public ModelAndView getLeave(@PathVariable("id") Long id) {
    	 ModelAndView mav = new ModelAndView("modules/act/oaleave/leavehandle");
        Leave leave = actLeaveService.getLeave(id);
        List<Comment> list = new ArrayList<Comment>();
        list = taskService.getProcessInstanceComments(leave.getProcessInstanceId());
        mav.addObject("detail", leave);
        mav.addObject("commentlist", list);
        return mav;
    }

}
